package src.ai.utils;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.UUID;

public class FileUtil {

    //本地文件存储路径
    public static final String LOCAL_STORAGE = "local_store/picture/";

    /**
     * 将文件内容，读取为字符串格式
     * multipartFile.getBytes()会将整个文件加载到内存中，对于大文件，这可能会导致 OutOfMemoryError 异常。
     * transferTo() 方法通常比 getBytes() 方法更快，因为它使用更少的系统调用。
     * IOUtils.copy() 方法在处理大文件时可能比 getBytes() 方法更有效，因为它使用缓冲 I/O。（如果文件超过1MB，推荐IOUtils.copy()）
     * @param multipartFile
     * @return
     * @throws IOException
     */
    public static String file2String(MultipartFile multipartFile) throws IOException {
        File file = File.createTempFile("AI_transfer", "tmp");
        multipartFile.transferTo(file);

        if (file.length() > 1024 * 1024 * 1024) {
            throw new IOException("File is too large");
        }

        StringBuilder sb = new StringBuilder((int) (file.length()));
        // 创建字节输入流
        FileInputStream fis = new FileInputStream(file);
        // 创建一个长度为10240的Buffer
        byte[] bbuf = new byte[10240];
        // 用于保存实际读取的字节数
        int hasRead = 0;
        while ( (hasRead = fis.read(bbuf)) > 0 ) {
            sb.append(new String(bbuf, 0, hasRead));
        }
        fis.close();
        if (file.exists()) {
            file.delete();
        }

        return sb.toString();
    }

    /**
     * 将文件内容，读取为字节数组格式
     * @param multipartFile
     * @return
     * @throws IOException
     */
    public static byte[] file2Bytes(MultipartFile multipartFile) throws IOException {
        byte[] bytes;
        File file = File.createTempFile("prefix", "suffix");
        multipartFile.transferTo(file);
        ByteArrayOutputStream bos = new ByteArrayOutputStream((int) file.length());
        BufferedInputStream in = null;

        try {
            in = new BufferedInputStream(new FileInputStream(file));
            short bufSize = 1024;   //缓冲区大小
            byte[] buffer = new byte[bufSize];
            int len1;
            while (-1 != (len1 = in.read(buffer, 0, bufSize))) {
                bos.write(buffer, 0, len1);
            }

            byte[] var7 = bos.toByteArray();
            return var7;
        } finally {
            // 删除临时文件
            if (file != null && file.exists()) {
                boolean deleted = file.delete();
                if (!deleted) {
                    throw new IOException("Failed to delete temporary file: " + file.getAbsolutePath());
                }
            }

            try {
                if (in != null) {
                    in.close();
                }
            } catch (IOException var14) {
                var14.printStackTrace();
            }

            bos.close();
        }
    }

    /**
     * 读取文件内容，作为字符串返回
     */
    public static String readFileAsString(String filePath) throws IOException {
        File file = new File(filePath);
        if (!file.exists()) {
            throw new FileNotFoundException(filePath);
        }

        if (file.length() > 1024 * 1024 * 1024) {
            throw new IOException("File is too large");
        }

        StringBuilder sb = new StringBuilder((int) (file.length()));
        // 创建字节输入流
        FileInputStream fis = new FileInputStream(filePath);
        // 创建一个长度为10240的Buffer
        byte[] bbuf = new byte[10240];
        // 用于保存实际读取的字节数
        int hasRead = 0;
        while ( (hasRead = fis.read(bbuf)) > 0 ) {
            sb.append(new String(bbuf, 0, hasRead));
        }
        fis.close();
        return sb.toString();
    }

    /**
     * 根据文件路径读取byte[] 数组
     */
    public static byte[] readFileByBytes(String filePath) throws IOException {
        File file = new File(filePath);
        if (!file.exists()) {
            throw new FileNotFoundException(filePath);
        } else {
            ByteArrayOutputStream bos = new ByteArrayOutputStream((int) file.length());
            BufferedInputStream in = null;

            try {
                in = new BufferedInputStream(new FileInputStream(file));
                short bufSize = 1024;
                byte[] buffer = new byte[bufSize];
                int len1;
                while (-1 != (len1 = in.read(buffer, 0, bufSize))) {
                    bos.write(buffer, 0, len1);
                }

                byte[] var7 = bos.toByteArray();
                return var7;
            } finally {
                try {
                    if (in != null) {
                        in.close();
                    }
                } catch (IOException var14) {
                    var14.printStackTrace();
                }

                bos.close();
            }
        }
    }

    /**
     * 文件上传至本地，如果成功返回文件绝对地址，如果失败返回 ConstUtil.FAIL_CODE
     * @param file
     * @return
     */
    public static String uploadFile(MultipartFile file){
        try {
            // 确保上传目录存在，如果不存在则创建
            Path directoryPath = Paths.get(LOCAL_STORAGE);
            if (!Files.exists(directoryPath)) {
                Files.createDirectories(directoryPath);
            }

            // 获取上传文件的原始文件名
            String originalFilename = file.getOriginalFilename();
            // 生成新的文件名
            String filename = UUID.randomUUID()+ originalFilename;
            // 构造上传文件的存储路径
            Path filePath = Paths.get(LOCAL_STORAGE, filename);
            // 将文件保存到指定路径
            Files.write(filePath, file.getBytes());
            return LOCAL_STORAGE + filename;
        } catch (IOException e) {
            return ConstUtil.FAIL_CODE;
        }
    }
}